﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Models.Base;
using WFI.BLL;
using System.ServiceModel;

namespace WFIServiceBehaviorExtension.Management
{
    public class AccessManage
    {
        public static readonly AccessManage _accessManage = new AccessManage();
        /// <summary>
        /// 当前用户
        /// </summary>
        public static UserInfo CurrentUser { get; set; }

        /// <summary>
        /// 单位 秒S
        /// </summary>
        public static int ThrottleUnit { get; set; }
        /// <summary>
        /// 阀值
        /// </summary>
        public static int ThrottleNum { get; set; }
        /// <summary>
        /// 取得head对应该的Value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private string GetHeaderValue(string key)
        {

            int index = OperationContext.Current.IncomingMessageHeaders.FindHeader(key, "http://www.wfi.cn");

            if (index >= 0)
            {
                return OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(index).ToString();
            }


            return null;
        }

        /// <summary>
        /// 验证用户名密码
        /// </summary>
        /// <param name="errMsg">错误信息</param>
        /// <returns>是否成功</returns>
        public bool IsUserInfoByName(out string errMsg)
        {
            string userName = GetHeaderValue("OperationUserName");
            string pwd = GetHeaderValue("OperationPwd");
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwd))
            {
                errMsg = "操作的用户名或密码为空！";
                return false;
            }

            List<UserInfo> userList = baseAccessManage._baseAccessManage.GetAllUserInfo();
            UserInfo u = userList.Where(p => p.u_Name.ToLower().Equals(userName.ToLower())).FirstOrDefault();

            if (u == null)
            {
                errMsg = "操作的用户名不正确！";
                return false;
            }
            else
            {
                //1.密码验证
                if (!string.Equals(u.u_Pwd, WFI.common.Extension.encryptionManage.md5(pwd, WFI.common.Enumeration.MDLength.MD64), StringComparison.CurrentCultureIgnoreCase))
                {
                    errMsg = "操作的密码不正确！";
                    return false;
                  
                }
            }
            CurrentUser = u;
            errMsg = "验证成功！";
            //测试用
           // baseAccessManage._baseAccessManage.InsertUserInfo();
           //List<UserInfo> userList2= baseAccessManage._baseAccessManage.GetAllUserInfo();
            return true;
        }

        /// <summary>
        /// 用户是否有权限执行这个方法
        /// </summary>
        /// <param name="executeFunction"></param>
        /// <returns></returns>
        public bool IsUserPermissions(string executeFunction,out string msg)
        {

            if (CurrentUser != null)
            {
                //1.用户对应的组
                List<UserLinkGroup> userLink = baseAccessManage._baseAccessManage.GetAllUserLinkGroup().Where(p => p.u_Id.Equals(CurrentUser.u_Id)).ToList();
                if (userLink != null && userLink.Count>0)
                {
                    //2.组是否有效
                   var groupList = (from g in baseAccessManage._baseAccessManage.GetAllGroupInfo()
                             where (from t in userLink select t.g_Id).Contains(g.g_Id)
                             select g).ToList();
                  GroupInfo ginfo=groupList.OrderByDescending(o => o.lastModifyTime).FirstOrDefault();
                  ThrottleNum = ginfo.ThrottleNum;
                  ThrottleUnit = ginfo.ThrottleUnit;

                   if (groupList != null && groupList.Count>0)
                   {
                       //3.组对应的功能
                       var functLinkList = (from f in baseAccessManage._baseAccessManage.GetAllGroupLinkFunction()
                                            where (from t in groupList select t.g_Id).Contains(f.g_Id)
                                            select f).ToList();
                       if (functLinkList != null && functLinkList.Count > 0)
                       {
                           //4.组对应的功能
                           var functList = (from fun in baseAccessManage._baseAccessManage.GetAllFunction()
                                            where (from t in functLinkList select t.f_Id).Contains(fun.f_Id)
                                            select fun).ToList();
                           if (functList != null && functList.Count > 0)
                           {
                               //5.用户所在的组可以执行该方法
                               var function = functList.Where(f => string.Equals(f.f_Action.Trim(), executeFunction, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                               if (function != null && !string.IsNullOrEmpty(function.f_Action))
                               {
                                   msg = "用户所在的组可以执行该方法!";
                                   return true;
                               }
                               else
                               {
                                   msg = string.Format("用户:{0}所在的组没有授权该方法({1}),请联系管理员!", CurrentUser.u_Name, executeFunction);
                                   return false;
                               }
                           }
                           else
                           {
                               msg = "用户所在的组授权的功能无效,请联系管理员!";
                               return false;
                           }
                       }
                       else
                       {
                           msg = "用户所在的组未授权功能,请联系管理员!";
                           return false;
                       } 
                   }
                   else
                   {
                       msg = "用户所在的组无效,请联系管理员!";
                       return false;
                   }
                }
                else
                {
                    msg = "此用户没有加入组,请联系管理员!";
                    return false;
                }
            }
            else
            {
                msg = "用户未验证或验证不通过！";
                return false;
            }
        }

    }
}
